package com.originskyseed.platform.user.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import com.originskyseed.platform.core.util.bean.PrimaryKeyGeneratorUtil;
import com.originskyseed.platform.user.model.PlayerRelateChannelLog;
import com.originskyseed.platform.user.service.IPlayerRelateChannelLogService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.originskyseed.platform.common.api.util.QueryAppUtil;
import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.filter.helper.SingleSignOnTokenHelper;
import com.originskyseed.platform.user.i18n.UserResponseMsg;
import com.originskyseed.platform.user.model.Player;
import com.originskyseed.platform.user.model.PlayerRelateChannelApply;
import com.originskyseed.platform.user.model.UserInfo;
import com.originskyseed.platform.user.service.IPlayerRelateChannelApplyService;
import com.originskyseed.platform.user.service.IPlayerService;
import com.originskyseed.platform.user.vo.request.PlayerRelateChannelApplyRequestVO;

/**
 * 玩家渠道申请信息表Controller类（OSI_PLAYER_RELATE_CHANNEL_APPLY）
 *
 * @author WuZhuoXi
 */
@Controller
@RequestMapping("/playerRelateChannelApply")
@BaseLocaleResource(localeFileName = "i18n_user")
public class PlayerRelateChannelApplyController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(PlayerRelateChannelApplyController.class);

	@DubboReference
	private IPlayerRelateChannelApplyService playerRelateChannelApplyService;

	@DubboReference
	private IPlayerRelateChannelLogService playerRelateChannelLogService;

	@DubboReference
	private IPlayerService playerService;

	/**
	 * 分页查询
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/playerRelateChannelApplyList.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<PlayerRelateChannelApply>> playerRelateChannelApplyList(HttpServletRequest request) {
		BaseResponseBody<BasePage<PlayerRelateChannelApply>> result = null;
		try {
			// 请求对象
			PlayerRelateChannelApplyRequestVO requestVO = this.getParameterBean(PlayerRelateChannelApplyRequestVO.class);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			if (userInfo!=null&&userInfo.getSourceSys()==1) {
				requestVO.setCreatorId(userInfo.getId());
			}
			// 分页查询
			BasePage<PlayerRelateChannelApply> page = new BasePage<PlayerRelateChannelApply>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.playerRelateChannelApplyService.selectListByPage(requestVO.toMap(), page);
			result = new BaseResponseBody<BasePage<PlayerRelateChannelApply>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<PlayerRelateChannelApply>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 保存信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/playerRelateChannelApplySave.json", method = RequestMethod.POST)
	@RequiredParams(names = {})
	public BaseResponseBody<PlayerRelateChannelApply> playerRelateChannelApplySave(HttpServletRequest request) {
		BaseResponseBody<PlayerRelateChannelApply> result = null;
		try {
			// 获取当前用户信息
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);

			// 请求对象
			PlayerRelateChannelApply playerRelateChannelApply = this.getParameterBean(PlayerRelateChannelApply.class);
			if (StringUtils.isNotBlank(playerRelateChannelApply.getId())) {
				this.playerRelateChannelApplyService.updateByPrimaryKeySelective(playerRelateChannelApply);
			} else {
				// 查询玩家信息,工会id
				Player queryPlayer = this.playerService.selectByPlayerId(playerRelateChannelApply.getPlayerId());
				if(queryPlayer==null)
				{
					result = new BaseResponseBody<PlayerRelateChannelApply>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.PLAYER_DATA_NOEXIST.getMsg()),"", null);
					return result;
				}
				String id= PrimaryKeyGeneratorUtil.getInstance().getRandomKey();
				playerRelateChannelApply.setId(id);
				playerRelateChannelApply.setOldChannelId(queryPlayer.getChannelId());
				playerRelateChannelApply.setOldChannelSubId(queryPlayer.getChannelSubId());
				playerRelateChannelApply.setCreator(userInfo.getName());
				playerRelateChannelApply.setCreatorId(userInfo.getId());
				playerRelateChannelApply.setState(1);
				this.playerRelateChannelApplyService.insertSelective(playerRelateChannelApply);

				String groupId = "";
				// 接口请求
				TreeMap<String, Object> paramMap = new TreeMap<>();
				paramMap.put("channelId", queryPlayer.getChannelSubId());
				Map map = QueryAppUtil.query("queryUnionUrl", 1, paramMap);
				Integer code = Integer.parseInt(map.get("code").toString());
				if (code == 1) {
					String data = (String) map.get("data");
					JSONObject jsonObject = JSONObject.parseObject(data);
					groupId = jsonObject.getString("tradeUnionId");
				}

				// 接口请求
				paramMap = new TreeMap<>();
				paramMap.put("vvId", playerRelateChannelApply.getPlayerId());
				paramMap.put("newScId", playerRelateChannelApply.getChannelSubId());
				paramMap.put("segmentingLine", playerRelateChannelApply.getChangeChannelTime());
				paramMap.put("recordType", playerRelateChannelApply.getType());
				paramMap.put("opType", playerRelateChannelApply.getType());
				paramMap.put("tieUpReason", playerRelateChannelApply.getRemark());
				paramMap.put("groupId", groupId);
				paramMap.put("loginName", userInfo.getName());
				map = QueryAppUtil.query("playerChannelUrl", 2, paramMap);
				code = Integer.parseInt(map.get("code").toString());
				String msg=map.get("msg").toString();
				if (code == 1) {
					PlayerRelateChannelLog playerRelateChannelLog=new PlayerRelateChannelLog();
					playerRelateChannelLog.setPlayerId(playerRelateChannelApply.getPlayerId());
					playerRelateChannelLog.setChannelId(playerRelateChannelApply.getChannelId());
					playerRelateChannelLog.setChannelSubId(playerRelateChannelApply.getChannelSubId());
					playerRelateChannelLog.setChangeChannelTime(playerRelateChannelApply.getChangeChannelTime());
					playerRelateChannelLog.setOldChannelId(queryPlayer.getChannelId());
					playerRelateChannelLog.setOldChannelSubId(queryPlayer.getChannelSubId());
					playerRelateChannelLog.setSource(0);
					playerRelateChannelLog.setIsUpdate(0);
					this.playerRelateChannelLogService.insertSelective(playerRelateChannelLog);

					playerRelateChannelApply.setState(2);
					playerRelateChannelApply.setReviewResult(msg);
					this.playerRelateChannelApplyService.updateByPrimaryKeySelective(playerRelateChannelApply);
				}
				else
				{
					playerRelateChannelApply.setState(3);
					playerRelateChannelApply.setReviewResult(msg);
					this.playerRelateChannelApplyService.updateByPrimaryKeySelective(playerRelateChannelApply);
					result = new BaseResponseBody<PlayerRelateChannelApply>(true, CommonResponseCode.SUCCESS.getCode(), msg, playerRelateChannelApply);
					return  result;
				}
			}
			result = new BaseResponseBody<PlayerRelateChannelApply>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_SUCCESS.getMsg()), playerRelateChannelApply);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<PlayerRelateChannelApply>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 删除信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/playerRelateChannelApplyDelete.json", method = RequestMethod.POST)
	@RequiredParams(names = { "ids" })
	public BaseResponseBody<Boolean> playerRelateChannelApplyDelete(HttpServletRequest request) {
		BaseResponseBody<Boolean> result = null;
		try {
			// 请求参数
			String[] ids = this.getParameterArray("ids", new String[] {});

			this.playerRelateChannelApplyService.deleteByPrimaryKeys(Arrays.asList(ids));
			result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 玩家改绑申请
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/playerChangeChannel.json", method = RequestMethod.POST)
	@RequiredParams(names = { "playId", "channelId" })
	public BaseResponseBody<Boolean> playerChangeChannel(HttpServletRequest request) {
		BaseResponseBody<Boolean> result = null;
		try {
			// 请求参数
			String playId = this.getParameterString("playId", null);
			String channelSubId = this.getParameterString("channelSubId", null);
			// 接口请求
			TreeMap<String, Object> paramMap = new TreeMap<>();
			paramMap.put("playId", playId);
			paramMap.put("newScId", channelSubId);
			Map map = QueryAppUtil.query("playerChannelUrl", 2, paramMap);
			Integer code = Integer.parseInt(map.get("code").toString());
			if (code == 1) {
				result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.POST_DATA_SUCCESS.getMsg()), true);
			} else {
				return new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), "") + "msg: " + (String) map.get("msg"), null);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.POST_DATA_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

}
